package com.earogya.logic.medical_records;

import java.io.IOException;
import ca.uhn.hl7v2.HL7Exception;
import ca.uhn.hl7v2.model.Message;
import ca.uhn.hl7v2.model.v251.message.ADR_A19;
import ca.uhn.hl7v2.model.v251.segment.MSH;
import ca.uhn.hl7v2.parser.EncodingNotSupportedException;
import ca.uhn.hl7v2.parser.GenericParser;
import ca.uhn.hl7v2.parser.Parser;

/**
 * Accepts a HL7 message as a string and creates HL7 Message object.
 * @author Chamendri
 *
 */
public class HL7Parser {

	private String message;
	
	/**
	 * Accepts HL7 message as a string
	 * @param message
	 */
	public HL7Parser(String message){
		this.message=message;
	}
	
	/**
	 * Parse the HL7 string and creates the relevant object.
	 * @return Object
	 */
	public Object getMessageAsObject(){
		Parser p = new GenericParser();
		Object messageObject=null;
		 Message hapiMsg;
		 try {
		 // The parse method performs the actual parsing
			 hapiMsg = p.parse(message);
		 	 MSH mshSegment=(MSH)hapiMsg.get("MSH");
		 	 String msgType=mshSegment.getMessageType().getMessageCode().getValue();
			 String msgTrigger = mshSegment.getMessageType().getTriggerEvent().getValue();
			 messageObject=identifyMessage(msgType, msgTrigger, hapiMsg);
			 System.out.println(msgType+" "+msgTrigger);
		 } catch (EncodingNotSupportedException e) {
			 e.printStackTrace();
		 } catch (HL7Exception e) {
			 e.printStackTrace();
		} catch (IOException e) {
			 e.printStackTrace(); 
		}	
		return messageObject;
	}
	
	/**
	 * Identify the HL7 message based on the trigger event and the message code
	 * @param messageCode
	 * @param triggerEvent
	 * @param hapiMsg
	 * @return Object
	 * @throws IOException
	 * @throws HL7Exception
	 */
	private Object identifyMessage(String messageCode, String triggerEvent, Message hapiMsg) throws IOException, HL7Exception{
		Object obj=null;
		if(messageCode.equals("ADR") && triggerEvent.equals("A19")){
				ADR_A19 adr=(ADR_A19)hapiMsg;
				obj=adr;
		}else{
			System.out.println("Unexpected trigger event");
		}
		return obj;
	}
}
